package com.example.sharedpreference;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private Button loginButton;
	private EditText emailEdit;
	private EditText passwordEdit;
	private CheckBox autoLoginCheck;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i("MainActivity", "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		loginButton = (Button) findViewById(R.id.loginButton);
		emailEdit = (EditText) findViewById(R.id.emailEdit);
		passwordEdit = (EditText) findViewById(R.id.passwordEdit);
		autoLoginCheck = (CheckBox) findViewById(R.id.autoLoginCheck);

		loginButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 1. 입력 계정 유효성 체크
				String email = emailEdit.getText().toString();
				String password = passwordEdit.getText().toString();

				if (LoginUtils.isValid(email, password)) {
					// 2. 자동 로그인 여부 체크
					if (autoLoginCheck.isChecked()) {
						SharedPreferences prefs = getSharedPreferences(
								"LoginPref", MODE_PRIVATE);

						SharedPreferences.Editor ed = prefs.edit();
						ed.putBoolean("auto_login", true);
						ed.putString("email", email);
						ed.putString("password", password);
						ed.commit();
					}
					Intent intent = new Intent(MainActivity.this,
							HomeActivity.class);
					startActivity(intent);
					finish();
				} else {
					// 입력된 계정이 유효하지 않으므로 재입력 요구
					Toast.makeText(MainActivity.this, R.string.invalid,
							Toast.LENGTH_SHORT).show();
				}
			}
		}); // setOnClickListener

		// 자동 로그인 여부 확인
		SharedPreferences prefs = getSharedPreferences("LoginPref",
				MODE_PRIVATE);

		boolean autoLogin = prefs.getBoolean("auto_login", false);
		if (autoLogin) {
			// 저장된 계정 유효성 체크
			String account = prefs.getString("email", "");
			String password = prefs.getString("password", "");

			if (LoginUtils.isValid(account, password)) {
				Intent intent = new Intent(MainActivity.this,
						HomeActivity.class);
				startActivity(intent);
				finish();
			} else {
				// 저장된 계정이 유효하지 않으므로 자동 로그인 해제
				SharedPreferences.Editor ed = prefs.edit();
				ed.putBoolean("auto_login", false);
				ed.commit();
			}
		} else {
			// 저장된 자동 로그인 정보가 없을
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
